package com.mlizhi.base;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;

import org.json.JSONObject;

import com.android.volley.AuthFailureError;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import com.mlizhi.kingdom.R;
import com.mlizhi.modules.spec.util.JsonUtil;
import com.mlizhi.utils.Constants;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.app.AlertDialog.Builder;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.DialogInterface.OnClickListener;
import android.net.Uri;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.text.Html;
import android.view.ContextThemeWrapper;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ProgressBar;
import android.widget.Toast;

public class VersionManager {

	private Activity activity;
	private String apkUrl = "";
	/**
	 * 更新描述文案对话框
	 */
	private Dialog noticeDialog;
	/**
	 * 下载对话框
	 */
	private Dialog downloadDialog;
	@SuppressLint("SdCardPath")
	private String savePath = "";
	// 保存路径
	private String saveFileName = "";
	// 下载进度条
	private ProgressBar mProgress;

	// 更新进度
	private static final int DOWN_UPDATE = 1;
	// 下载完成
	private static final int DOWN_OVER = 2;

	private int progress;
	// 下载用的多线程
	private Thread downLoadThread;

	private boolean interceptFlag = false;

	private RequestQueue mRequestQueue;
	
	private ProgressDialog versionProgressDialog;

	/**
	 * 控制Ui组件的
	 */
	private Handler mHandler = new Handler() {
		public void handleMessage(Message msg) {
			switch (msg.what) {
			case DOWN_UPDATE:
				mProgress.setProgress(progress);
				break;
			case DOWN_OVER:
				installApk();
				break;
			default:
				break;
			}
		};
	};

	/**
	 * 构造方法
	 * 
	 * @param activity
	 */
	public VersionManager(Activity activity) {
		this.activity = activity;

	}
	
	// 判断外部存储是否可以读写
	public boolean isExternalStorageWritable() {
		String state = Environment.getExternalStorageState();
		if (Environment.MEDIA_MOUNTED.equals(state)) {
			return true;
		}
		return false;
	}

	// 判断外部存储是否至少可以读
	public boolean isExternalStorageReadable() {
		String state = Environment.getExternalStorageState();
		if (Environment.MEDIA_MOUNTED.equals(state)
				|| Environment.MEDIA_MOUNTED_READ_ONLY.equals(state)) {
			return true;
		}
		return false;
	}

	/**
	 * 显示说明
	 * 
	 * @param downloadUrl
	 * @param descn
	 */
	public void showNoticeDialog(String downloadUrl, String descn) {
		apkUrl = downloadUrl;
		if(isExternalStorageWritable()){
			savePath = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS).getPath();
		}else{
			savePath = activity.getFilesDir().getPath();
		}
		saveFileName = savePath+  downloadUrl.substring(downloadUrl.lastIndexOf("/"), downloadUrl.length());
		AlertDialog.Builder builder = new Builder(activity);
		builder.setTitle(activity.getString(R.string.download_info_title));
		builder.setMessage(Html.fromHtml(descn));
		builder.setPositiveButton(
				activity.getString(R.string.download_info_yes),
				new OnClickListener() {
					@Override
					public void onClick(DialogInterface dialog, int which) {
						dialog.dismiss();
						showDownloadDialog();
					}
				});
		builder.setNegativeButton(
				activity.getString(R.string.download_info_no),
				new OnClickListener() {
					@Override
					public void onClick(DialogInterface dialog, int which) {
						dialog.dismiss();
					}
				});
		noticeDialog = builder.create();
		noticeDialog.show();
	}

	/**
	 * 下载过程进度对话框
	 */
	private void showDownloadDialog() {
		AlertDialog.Builder builder = new Builder(new ContextThemeWrapper(
				activity, R.style.MlzThemeDialog));
		builder.setTitle(activity.getResources().getString(
				R.string.download_info_title));

		final LayoutInflater inflater = LayoutInflater.from(activity);
		View v = inflater.inflate(R.layout.progress, null);
		mProgress = (ProgressBar) v.findViewById(R.id.progress);

		builder.setView(v);
		builder.setNegativeButton(
				activity.getResources()
						.getString(R.string.download_info_concel),
				new OnClickListener() {
					@Override
					public void onClick(DialogInterface dialog, int which) {
						dialog.dismiss();
						interceptFlag = true;
					}
				});
		downloadDialog = builder.create();
		downloadDialog.show();

		downloadApk();
	}

	private Runnable mdownApkRunnable = new Runnable() {
		@Override
		public void run() {
			try {

				URL url = new URL(apkUrl);

				HttpURLConnection conn = (HttpURLConnection) url
						.openConnection();
				conn.connect();
				int length = conn.getContentLength();
				InputStream is = conn.getInputStream();

				File file = new File(savePath);
				if (!file.exists()) {
					file.mkdir();
				}
				String apkFile = saveFileName;
				File ApkFile = new File(apkFile);
				FileOutputStream fos = new FileOutputStream(ApkFile);

				int count = 0;
				byte buf[] = new byte[1024];

				do {
					int numread = is.read(buf);
					count += numread;
					progress = (int) (((float) count / length) * 100);
					// 更新进度
					mHandler.sendEmptyMessage(DOWN_UPDATE);
					if (numread <= 0) {
						// 下载完成通知安装
						mHandler.sendEmptyMessage(DOWN_OVER);
						break;
					}
					fos.write(buf, 0, numread);
				} while (!interceptFlag);// 点击取消就停止下载.

				fos.close();
				is.close();
			} catch (MalformedURLException e) {
				e.printStackTrace();
			} catch (IOException e) {
				e.printStackTrace();
			}

		}
	};

	/**
	 * 下载apk
	 * 
	 * @param url
	 */

	private void downloadApk() {
		downLoadThread = new Thread(mdownApkRunnable);
		downLoadThread.start();
	}

	/**
	 * 安装apk
	 * 
	 * @param url
	 */
	private void installApk() {
		File apkfile = new File(saveFileName);
		if (!apkfile.exists()) {
			return;
		}
		Intent i = new Intent(Intent.ACTION_VIEW);
		i.setDataAndType(Uri.parse("file://" + apkfile.toString()),
				"application/vnd.android.package-archive");
		activity.startActivity(i);

	}

	
	private boolean implicit = false;
	/**
	 * 检测对话框
	 * @param implicit 是否是隐式检测
	 */
	public void showVersionProcessDialog(boolean implicit) {
		this.implicit = implicit;
		if(!implicit) {
			versionProgressDialog = ProgressDialog.show(activity, "", "正在获取新版本……" ,true, false);
		}
		boolean netUsable = NetWorkManager.getNewInstance().isNetworkConnected(activity);
		if (netUsable) {
			mRequestQueue = Volley.newRequestQueue(activity);
			// Request a string response from the provided URL.
			StringRequest stringRequest = new StringRequest(
					Request.Method.POST, Constants.URL_POST_GET_NEW_VERSION,successListener, errorListener) {
				@Override
				protected Map<String, String> getParams() throws AuthFailureError {
					String timestamp = SecurityUtil.getTimestamp();
					Map<String, String> params = new HashMap<String, String>();
					params.put("companyId", Constants.COMPANY_ID);
					params.put("type", Constants.DEVICE_TYPE);
					params.put(Constants.URL_TIMESTAMP, timestamp);
					params.put(Constants.URL_KEY,SecurityUtil.getMd5String(timestamp));
					return params;
				}
			};
			mRequestQueue.add(stringRequest);
			mRequestQueue.start();
		} else {
			Toast.makeText(activity, R.string.net_connected_failure,Toast.LENGTH_SHORT).show();
		}
	}
	
	Response.Listener<String> successListener = new Response.Listener<String>() {
		@Override
		public void onResponse(String response) {
			String code = JsonUtil.getHeaderCode(response);
			if (Constants.RESULT_JSON_HEADER_CODE_SUCCESS.equals(code)) {
				if(!implicit){
					versionProgressDialog.dismiss();
				}
				try {
					JSONObject jsonObject = new JSONObject(response);
					if(jsonObject.has("version") && !jsonObject.isNull("version")){
						JSONObject versionObj = JsonUtil.getBodyJsonObject(response).getJSONObject("version");

						String versionNo = versionObj.getString("versionNo");
						String downloadUrl = versionObj.getString("download");
						String descn = versionObj.getString("descn");
						Session mSession = Session.get(activity);
						int currentVersion = mSession.getVersionCode();
						int serverVersion = (int) Float.parseFloat(versionNo);

						if (serverVersion > currentVersion) {
							showNoticeDialog(downloadUrl, descn);
						}else{
							if(!implicit) {
								Toast.makeText(activity, "没有发现新版本！！！", Toast.LENGTH_SHORT).show();
							}
						}
					}
				} catch (Exception e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}

			} else {
//				Toast.makeText(activity,JsonUtil.getHeaderErrorInfo(response),Toast.LENGTH_SHORT).show();
			}
		}
	};
	
	
	Response.ErrorListener errorListener = new Response.ErrorListener() {
		@Override
		public void onErrorResponse(VolleyError error) {
			Toast.makeText(activity, error.getMessage(),Toast.LENGTH_SHORT).show();
			if(!implicit){
				versionProgressDialog.dismiss();
			}
		}
	};
	
}
